package com.ruoyi.web.controller.identify;

import com.ruoyi.common.core.redis.RedisCache;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Anonymous;

import javax.annotation.Resource;
import java.io.*;
import java.lang.*;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.TimeUnit;


/*
文件上传、显示功能
 */

@Anonymous
@RestController
@RequestMapping("/identify")
public class IdentifyController {

    @Resource
    private RedisCache redisCache;
    private static final String photoLocationPrefix = "identify:photo:";

    //todo
    //workingDir 需配置为Python脚本需要的资源所在的目录
    String workingDir = "D:\\\\86135\\\\Desktop\\\\Yolov5_StrongSORT_OSNet-3.0\\\\Yolov5_StrongSORT_OSNet-3.0\\\\yolov5";
    //该python3配置为本机满足yolov5环境的解释器
    String pythonEnvs = "C:\\\\Users\\\\86135\\\\.conda\\\\envs\\\\yolo5\\\\python";


    @PostMapping(value = "/handle",produces = {MediaType.IMAGE_JPEG_VALUE})
    public byte[] handleImage(@RequestParam("file") MultipartFile file) throws IOException{
        //上传功能
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                File uploadFile = new File(workingDir+"\\\\data\\\\images\\\\5699.jpg");
                try (FileOutputStream fos = new FileOutputStream(uploadFile)) {
                    fos.write(bytes);
                }
                System.out.println("File upload successfully save at " + workingDir+"\\\\data\\\\images\\\\5699.jpg");
            } catch (Exception e) {
                return ("Failed to upload file!").getBytes();
            }
        }


        //识别功能
        ProcessBuilder pb = new ProcessBuilder(pythonEnvs,workingDir+"\\\\detect.py");
        pb.directory(new File(workingDir)); // 设置Python的工作目录
        pb.redirectErrorStream(true); // 合并标准输出和标准错误

        try {
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                // 获取识别图片存储位置
                if (line.contains("Results saved to")) {
                    String resultLocation = line.split("Results saved to ")[1];
                    redisCache.setCacheObject(photoLocationPrefix, resultLocation, 60, TimeUnit.SECONDS);
                }
            }
            int exitCode = process.waitFor();
            System.out.println("\nExited with error code : " + exitCode);
            if(exitCode == 0) {
                System.out.println("recognize successfully");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        Object cacheObject = redisCache.getCacheObject(photoLocationPrefix);
        String imagePath = null;
        if (ObjectUtils.isNotEmpty(cacheObject)) {
            imagePath = workingDir +"\\\\"+ cacheObject +"\\\\5699.jpg";
        }
        else{
            String str = "无法识别图片";
            return str.getBytes();
        }
        File downloadFile = new File(imagePath);
        byte[] imageBytes = Files.readAllBytes(downloadFile.toPath());
        return imageBytes;

    }

}